package com.uniview.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.uniview.base.BaseDao;
import com.uniview.entity.po.ResourceRole;

@Repository("resourceRoleDao")
public class ResourceRoleDao extends BaseDao<ResourceRole> {

	/**
	 * 添加资源授权
	 * @param rList
	 * @return
	 * @throws Exception
	 */
	public boolean addResouceRole(List<ResourceRole> rList) throws Exception{
		if(!rList.isEmpty()){
			for (ResourceRole resourceRole : rList) {
				this.save(resourceRole);
			}
			
			return true;
		}
		return false;
	}
	
	/**
	 * 删除角色授权的所有资源
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	public boolean deleteResouceRoleWithRoleId(int roleId) throws Exception{
		return this.deleteByHql("delete ResourceRole where roleId = ? ", roleId);
	}
	
	/**
	 * 查找角色授权的资源列表
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	public List<ResourceRole> findResouceRoleWithRoleId(int roleId) throws Exception{
		return this.findByHql("from ResourceRole where roleId = ? ", roleId);
	}
	
	/**
	 * 根据登陆用户查询相应的授权资源
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public List<ResourceRole> findReousceRoleByUserId(String userId) throws Exception {
		String sql = "select * from un_resource_role r where exists (select roleId from un_user_role ur where ur.userId=? and r.roleId = ur.roleId)";
		return this.findBySql(sql, userId);
	}
	
	/**
	 * 根据mendId和roleId查询
	 * @param menuId
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	public ResourceRole findByMenuIdAndRoleId(Integer menuId,Integer roleId)throws Exception{
		String sql = "select * from sd_resource_role where MENUID=? and ROLEID=?";
		List<ResourceRole> list = this.findBySql(sql, menuId,roleId);
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 根据roleId和menuId删除
	 * @param menuId
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	public boolean delByMenuIdAndRoleId(Integer menuId,Integer roleId) throws Exception{
		String hql = "delete from ResourceRole WHERE menuId=? AND roleId=?";
		return deleteByHql(hql, menuId,roleId);
	}
	
}
